<!-- 车辆信息 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="车辆名称">
                            <a-input v-model="name" allow-clear placeholder="请输入车辆名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="车辆分类">
                            <a-select v-model="classificationId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in classifyList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="车辆标签">
                            <a-input v-model="tag" allow-clear placeholder="请输入车辆标签" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="是否热门">
                            <a-select v-model="isHot" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in isHotList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type="primary" style="margin-right: 20px" @click="getData()">查询</a-button>
                            <a-button type="" icon="plus" @click="add()">添加</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small">
            <div slot="classificationId" slot-scope="classificationId">
                <div v-for="(item,i) in classifyList" :key="item.id">
                    <a-tag v-if="item.id == classificationId" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="imageUrl" slot-scope="text,record">
                <img style="width: 120px;height: 60px" v-if="record.imageUrl && record.imageUrl.substring(0,4) == 'http'" :src="record.imageUrl && record.imageUrl.split(',')[0]" alt="" @click="showImg(record.imageUrl)">
                <div v-else>-</div>
            </div>
            <div slot="instruction" slot-scope="instruction">
                <span v-for="(item,i) in instruction.split(',')" :key="item">
                    <a-tag :color="colors[i%13]">{{item}}</a-tag>
                </span>
            </div>
            <div slot="tag" slot-scope="tag">
                <span v-for="(item,i) in tag.split(',')" :key="item">
                    <a-tag :color="colors[i%13]">{{item}}</a-tag>
                </span>
            </div>
            <div slot="isHot" slot-scope="isHot">
                <div v-for="(item,i) in isHotList" :key="item.id">
                    <a-tag v-if="item.id == isHot" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="safeConfig" slot-scope="text,record">
                <a-button type="link" @click="setSafeConfig(record)">设置</a-button>
            </div>
            <div slot="paramConfig" slot-scope="text,record">
                <a-button type="link" @click="setParamConfig(record)">设置</a-button>
            </div>
            <div slot="detail" slot-scope="text,record">
                <a-button type="link" @click="setDetail(record)">设置</a-button>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="开" un-checked-children="关" disabled :checked="status == '1' ? true : false" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <a-button type="link" @click="update(record)">修改</a-button>
                <a-popconfirm
                    title="是否确认删除当前配置?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="del(record)"
                >
                    <a-button class="errorColor" type="link">删除</a-button>
                </a-popconfirm>
            </div>
        </a-table>

        <a-modal
            title="添加、修改车辆信息配置"
            :visible="visible"
            @ok="handleOk"
            :confirm-loading="confirmLoading"
            @cancel="visible = false"
            width="80%"
            >
            <div>
                <a-row :gutter='48'>
                    <a-col :md='10' :sm='24'>
                        <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
                            <a-form-item label="车辆分类">
                                <a-select v-model="item.classificationId" placeholder="请选择车辆分类" allowClear>
                                    <a-select-option v-for="(item,i) in classifyList" :key="i" :value="item.id.toString()">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item label="车辆名称">
                                <a-input v-model="item.name" placeholder="请输入车辆名称" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="车辆价格">
                                <a-input v-model="item.price" placeholder="请输入车辆价格" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="车辆市场价">
                                <a-input v-model="item.marketPrice" placeholder="请输入车辆市场价" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="车辆说明" help="说明之间用,隔开">
                                <a-input v-model="item.instruction" type="textarea" placeholder="例：经济型,5座,4门,自动挡,1.5T" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="车辆标签" help="标签之间用,隔开">
                                <a-input v-model="item.tag" type="textarea" placeholder="例：经典实用,品质可靠" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="排序">
                                <a-input v-model="item.sort" placeholder="请输入车辆标题排序" allow-clear></a-input>
                            </a-form-item>
                            <a-form-item label="状态">
                                <a-radio-group v-model="item.status" >
                                    <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                        </a-form>
                    </a-col>
                    <a-col :md='14' :sm='24'>
                        <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                            <a-form-item label="车辆主图">
                                <div class="clearfix">
                                    <a-upload
                                        list-type="picture-card"
                                        accept="image/*"
                                        :file-list="imgList"
                                        @preview="handlePreview"
                                        @change="imgHandleChange"
                                        :before-upload="beforeUpload"
                                    >
                                        <div v-if="imgList.length < 1">
                                            <a-icon type="plus" />
                                            <div class="ant-upload-text">选择车辆主图</div>
                                        </div>
                                    </a-upload>
                                </div>
                            </a-form-item>
                            <a-form-item label="轮播图片">
                                <div class="clearfix">
                                    <a-upload
                                        list-type="picture-card"
                                        accept="image/*"
                                        :file-list="fileList3"
                                        @preview="handlePreview"
                                        @change="handleChange3"
                                        :before-upload="beforeUpload"
                                    >
                                        <div v-if="fileList3.length < 10">
                                            <a-icon type="plus" />
                                            <div class="ant-upload-text">选择轮播图</div>
                                        </div>
                                    </a-upload>
                                </div>
                            </a-form-item>
                            <a-form-item label="参考样图">
                                <div class="clearfix">
                                    <a-upload
                                    list-type="picture-card"
                                    :file-list="fileList2"
                                    @preview="handlePreview"
                                    @change="handleChange2"
                                    >
                                    <div v-if="fileList2.length < 10">
                                        <a-icon type="plus" />
                                        <div class="ant-upload-text">
                                            选择图片
                                        </div>
                                    </div>
                                    </a-upload>
                                </div>
                            </a-form-item>
                        </a-form>
                    </a-col>
                </a-row>
            </div>
        </a-modal>

        <!-- 上传图片预览 -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        <!-- 表格图片预览 -->
        <a-modal :visible="previewImgVisible" :footer="null" @cancel="previewImgVisible = false">
            <a-carousel autoplay dots-class="slick-dots slick-thumb" arrows style="margin-bottom:60px">
                <div v-for="(img,i) in showImgs" :key="i">
                    <img :src="img" alt=""/>
                </div>
                <a slot="customPaging" slot-scope="props">
                    <img :src="getImgUrl(props.i)" />
                </a>
            </a-carousel>
        </a-modal>
    </div>
</template>

<script>
import { queryTravelVehicleClassify , queryTravelVehicleInfo , updateTravelVehicleInfo , queryTravelVehiclePicture , updateTravelVehiclePicture } from '@/api/travel';
import { columns } from './table';
import { uploadFile } from '@/api/brand';
import { getBase64 } from '@/utils/util';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            name: '', // 车辆名称
            tag: '', // 车辆标签
            isHot: undefined,
            isHotList: [
                { id: '0', name: '否',},{ id: '1', name: '是'}
            ],
            status: undefined,
            statusList: [
                { id: '1', name: '开启'},{ id: '0', name: '关闭'}
            ],
            classificationId: undefined,
            classifyList: [], // 分类列表
            dataList: [],
            total: 0,
            isload: false,
            page: 1,
            size: 10,
            columns,
            item: {
                'id': '',
                'name': '', // 名称
                'isHot': undefined, // 是否热门
                'classificationId': undefined, // 分类ID
                'price': '', // 价格
                'marketPrice': '', // 市场价
                'instruction': '', // 说明
                'tag': '', // 标签
                'imageUrl': '', // 图片地址
                'sort': '', // 排序
                'status': '1',
            },
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            confirmLoading: false,
            isAdd: false,
            visible: false,
            imgList: [],
            previewVisible: false,
            previewImage: '',
            previewImgVisible: false,
            showImgs: [],
            bannerList: [], // 轮播图
            fileList3: [],
            detailList: [], // 参考图
            fileList2: [],
        };
    },
    async created(){
        try {
            await this.queryClassify();
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 获取车辆分类信息
        queryClassify(){
            let _this = this
            return new Promise((resolve,reject) => {
                queryTravelVehicleClassify({'size': 99,'page': 0})
                .then(res=>{
                    if(res.success){
                        _this.classifyList = res.data.content;
                        resolve()
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 查询车辆信息
        getData(){
            let _this = this;
            _this.isload = true
            const params = {
                'brandId': _this.brandId,
                'name': _this.name,
                'classificationId': _this.classificationId,
                'tag': _this.tag,
                'isHot': _this.isHot,
                'status': _this.status,
                'sort': 'sort',
                'page': _this.page - 1,
                'size': _this.size,
            }
            queryTravelVehicleInfo(params)
            .then(res => {
                _this.isload = false
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements;
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData();
        },
        // 添加产品
        add(){
            this.item.id = ''
            this.item.name = '';
            this.item.classificationId = undefined;
            this.item.price = '';
            this.item.marketPrice = '';
            this.item.instruction = '';
            this.item.tag = '';
            this.item.sort = '1';
            this.item.imageUrl = '';
            this.item.status = '1';
            this.item.isHot = '0';
            this.imgList = [];
            this.bannerList = [];
            this.detailList = [];
            this.visible = true
        },
        // 修改产品
        async update(item){
            let _this = this;
            this.item = JSON.parse(JSON.stringify(item))
            _this.imgList = [];
            if(item.imageUrl && item.imageUrl.substring(0,4) == 'http'){
                var array = item.imageUrl.split(',');
                let _this = this;
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    _this.imgList.push({
                        'uid': index +1,
                        'id': index +1,
                        'url': element,
                        'status':'done',
                        'name':element,
                        'noFile': true,
                    })
                }
            }
            _this.bannerList = await _this._queryTravelVehiclePicture({vehicleId: item.id,type: '1'});
            _this.fileList3 = JSON.parse(JSON.stringify(_this.bannerList));
            _this.detailList = await _this._queryTravelVehiclePicture({vehicleId: item.id,type: '0'});
            _this.fileList2 = JSON.parse(JSON.stringify(_this.detailList));
            this.visible = true
        },
        // 确认添加、修改车型分类信息
        async handleOk(){ 
            let _this = this
            if(_this.item.classificationId == undefined){
                _this.$message.warning('请选择车辆类型')
                return;
            }
            if(_this.item.name == ''){
                _this.$message.warning('请输入车辆名称')
                return;
            }
            if(_this.item.price === ''){
                _this.$message.warning('请输入车辆价格')
                return;
            }
            if(_this.item.marketPrice === ''){
                _this.$message.warning('请输入车辆市场价')
                return;
            }
            var imgList = [];
            if(_this.imgList.length > 0){
                for (let index = 0; index < _this.imgList.length; index++) {
                    const element = _this.imgList[index];
                    console.log(element,'element')
                    if(element.noFile){
                        imgList.push(element.url);
                    }else{
                        try {
                            var imgs = await _this.uploadImg(element.originFileObj,`logo${index}`);
                            console.log(imgs,'imgs');
                            imgList.push(imgs);
                        } catch (error) {
                            _this.$notification['error']({
                                message: '提示',
                                description: error,
                                duration: 8,
                            })
                            return;
                        }
                    }
                }
                _this.item.imageUrl = imgList.join(',');
            }
            const params = {
                'id':_this.item.id,
                'brandId': _this.brandId,
                'classificationId': _this.item.classificationId,
                'name': _this.item.name,
                'price': _this.item.price,
                'marketPrice': _this.item.marketPrice,
                'instruction': _this.item.instruction.replace('，',','),
                'tag': _this.item.tag.replace('，',','),
                'imageUrl': _this.item.imageUrl,
                'isHot': _this.item.isHot,
                'sort': _this.item.sort,
                'status': _this.item.status,
            }
            updateTravelVehicleInfo(params)
            .then(async res=>{
                if(res.success){
                    _this.visible = false
                    _this.getData()
                    await _this._updateTravelVehiclePictureEvn('1',res.data.id)
                    await _this._updateTravelVehiclePictureEvn('0',res.data.id)
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id ? '修改成功' : '添加成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除产品
        del(item){
            let _this = this
            const params = {
                'id':item.id,
                'name': item.name,
                'imageUrl': item.imageUrl,
                'classificationId': item.classificationId,
                'sort': item.sort,
                'isHot': item.isHot,
                'status': item.status,
                'isDelete':'1',
            }
            updateTravelVehicleInfo(params)
            .then(async res=>{
                if(res.success){
                    _this.visible = false
                    _this.getData()
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 预览图片
        showImg(imgs){
            if(imgs){
                this.showImgs = imgs.split(',')
                console.log(this.showImgs,'imgs')
                this.previewImgVisible = true
            }
        },
        getImgUrl(i){
            return this.showImgs[i]
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        imgHandleChange({ fileList }) {
            this.imgList = fileList;
        },
        handleChange2({ fileList }) {
            this.fileList2 = fileList;
        },
        handleChange3({ fileList }) {
            this.fileList3 = fileList;
        },
        beforeUpload(file) {
            return false;
        },
        // 上传图片获取图片url
        uploadImg(file,name){
            let _this = this
            return new Promise((resolve,reject) => {
                let formData = new FormData()
                formData.append('brandId',_this.brandId)
                formData.append('urlName',name)
                formData.append('file',file)
                uploadFile(formData)
                .then(res=>{
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 查询车辆图片
        _queryTravelVehiclePicture({vehicleId,type}){
            let _this = this;
            return new Promise((resolve,reject) => {
                queryTravelVehiclePicture({vehicleId: vehicleId,type: type,page: 0,size: 99,brandId: _this.brandId})
                .then(res => {
                    if(res.success){
                        var imgList = [];
                        for (let index = 0; index < res.data.content.length; index++) {
                            const element = res.data.content[index];
                            imgList.push({
                                'uid': index +1,
                                'id': element.id,
                                'url': element.imageUrl,
                                'status':'done',
                                'name':element.imageUrl,
                                'noFile': true,
                            })
                        }
                        resolve(imgList);
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 增删改商品图片
        async _updateTravelVehiclePictureEvn(type,id){
            let _this = this;
            let add = []; // 删除
            let del = []; // 新增
            var array = [];
            var updateArray = [];
            if(type == '1'){
                array = _this.bannerList
                updateArray = _this.fileList3
            }else{
                array = _this.detailList
                updateArray = _this.fileList2
            }
            del = array.filter(x => !updateArray.some(y => y.id === x.id));
            console.log(del,'oldArr')
            for (let index = 0; index < updateArray.length; index++) {
                const item = updateArray[index];
                if(!item.id){
                    add.push(item);
                }
            }
            console.log(add,'add');
            // 添加
            if(add.length > 0){
                for (let index = 0; index < add.length; index++) {
                    const element = add[index];
                    var imgs = await _this.uploadImg(element.originFileObj,`image${index}`);
                    const params = {
                        'id': element.id,
                        'brandId': _this.brandId,
                        'vehicleId': id,
                        'imageUrl': imgs,
                        'type': type,
                    }
                    await _this._updateTravelVehiclePicture(params);
                }
            }
            // 删除
            if(del.length > 0){
                for (let index = 0; index < del.length; index++) {
                    const element = del[index];
                    const params = {
                        'id': element.id,
                        'isDelete': '1',
                        'brandId': _this.brandId,
                        'vehicleId': id,
                        'type': type,
                    }
                    await _this._updateTravelVehiclePicture(params);
                }
            }
        },
        _updateTravelVehiclePicture(params){
            return new Promise((resolve,reject) => {
                updateTravelVehiclePicture(params)
                .then(res => {
                    if(res.success){
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 门店保障
        setSafeConfig(item){
            this.$router.push({ path: '/vehicle/index/storeConfig',query: {'vehicleId': item.id,'vehicleName': item.name}})
        },
        // 参数
        setParamConfig(item){
            this.$router.push({ path: '/vehicle/index/paramConfig',query: {'vehicleId': item.id,'vehicleName': item.name}})
        },
        // 配置
        setDetail(item){
            console.log(item,'item')
            this.$router.push({ path: '/vehicle/index/details',query: {'vehicleId': item.id,'vehicleName': item.name}})
        },
    }
}

</script>
<style scoped>

</style>